﻿using FYSJcrm.Core.Common;
using FYSJcrm.Core.IRepository.PermManage;
using FYSJcrm.Core.IRepository.SystemManage;
using FYSJcrm.Core.Model.PermManage;
using FYSJcrm.Core.Web.Areas.PermManage.Models.RoleModels;
using FYSJcrm.Core.Web.Extensions.FilterExtensions;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace FYSJcrm.Core.Web.Areas.PermManage.Controllers
{
    [Area(nameof(PermManage))]
    public class RoleController : Controller
    {
        private readonly IManagerRoleRepository _managerRoleRepository;
        private readonly INavigationRepository _navigationRepository;

        public RoleController(IManagerRoleRepository managerRoleRepository, INavigationRepository navigationRepository)
        {
            _managerRoleRepository = managerRoleRepository;
            _navigationRepository = navigationRepository;
        }

        [CheckPermission("RoleManage.Show")]
        public IActionResult List()
        {
            return View();
        }

        [CheckPermission("RoleManage.Show")]
        public async Task<IActionResult> ListData(int page = 1, int limit = 10)
        {
            var managerRoles = await _managerRoleRepository.Select
                .Count(out long total)
                .Page(page, limit)
                .ToListAsync();

            return Json(new AjaxResult { Code = HttpCode.OK, Data = managerRoles, TotalCount = total });
        }

        [CheckPermission("RoleManage.Add")]
        public async Task<IActionResult> Add()
        {
            var navigations = await _navigationRepository.Select.ToTreeListAsync();

            return View(navigations);
        }

        [HttpPost]
        [CheckPermission("RoleManage.Add")]
        public async Task<IActionResult> Add(RoleAddModel model)
        {
            var roleName = await _managerRoleRepository.Select.Where(p => p.RoleName == model.RoleName).AnyAsync();
            if (roleName)
            {
                return Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "该角色已经存在" });
            }


            ManagerRoleEntity managerRole = new ManagerRoleEntity
            {
                RoleName = model.RoleName,
                Remark = model.Remark
            };

            var flag = await _managerRoleRepository.InsertRoleAsync(managerRole, model.PerNames);

            return flag ? Json(new AjaxResult { Code = HttpCode.OK, Data = "角色权限添加成功！" })
                    : Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "角色权限添加失败！" });
        }

        [CheckPermission("RoleManage.Edit")]
        public async Task<IActionResult> Edit(int id)
        {
            var managerRole = await _managerRoleRepository.Select.IncludeMany(p => p.Permissions, then => then.ToList()).Where(p => p.Id == id).FirstAsync();

            if (managerRole == null)
            {
                return View("Error", "id指定的角色信息不存在");
            }

            RoleEditViewModel viewModel = new RoleEditViewModel
            {
                Navigations = await _navigationRepository.Select.OrderBy(p => p.SortId).ToTreeListAsync(),
                Role = managerRole
            };

            return View(viewModel);
        }

        [HttpPost]
        [CheckPermission("RoleManage.Edit")]
        public async Task<IActionResult> Edit(RoleEditModel model)
        {
            var managerRole = await _managerRoleRepository.Select.Where(p => p.Id == model.RoleId).FirstAsync();

            if (managerRole == null)
            {
                return Json(new AjaxResult { Code = HttpCode.NotFound, ErrorMsg = "不存在该角色信息" });
            }

            var flag = await _managerRoleRepository.UpdateRoleAsync(managerRole, model.PerNames);

            return flag ? Json(new AjaxResult { Code = HttpCode.OK, Data = "修改角色权限成功！" })
                        : Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "修改角色权限失败！" });
        }

        [HttpPost]
        [CheckPermission("RoleManage.Delete")]
        public async Task<IActionResult> Delete(int id)
        {
            var flag = await _managerRoleRepository.DeleteRoleAsync(id);

            return flag ? Json(new AjaxResult { Code = HttpCode.OK, Data = "删除角色成功！" })
                : Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "删除角色失败！" });
        }

        [HttpPost]
        [CheckPermission("RoleManage.Delete")]
        public async Task<IActionResult> Delete(int[] selectedIds)
        {
            var count = await _managerRoleRepository.DeleteRoleAsync(selectedIds);

            return count > 0 ? Json(new AjaxResult { Code = HttpCode.OK, Data = "成功删除" + count + "个角色，删除失败" + (selectedIds.Length - count) + "个角色" })
                : Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "删除角色失败！" });
        }
    }
}
